package net.narusas.aceauction.push;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

import net.narusas.aceauction.push.model.Device;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
public class C2DMPushService implements PushService {
	private String host;
	private String auth;
	private String badgeText;

	@Override
	public void pushText(Device device, String message) {
		log.info("Device: {}", device);
		log.info("Message: {}", message);
		if (device == null || message == null) {
			return;
		}
		if (device.isAndroidSDevice() == false || device.isReady() == false) {
			return;
		}

		log.info("안드로이드에 메시지를 전송합니다.PUSH ID: {}", device.getPushToken());

		try {
			String regId = device.getPushToken();
			StringBuffer postDataBuilder = new StringBuffer();
			postDataBuilder.append("registration_id=" + regId);// 등록ID
			postDataBuilder.append("&collapse_key=1");
			postDataBuilder.append("&delay_while_idle=1");
			postDataBuilder.append("&data.title=" + URLEncoder.encode(message, "UTF-8"));// 제목
			postDataBuilder.append("&data.subtitle=" + URLEncoder.encode(message, "UTF-8"));// 제목
			postDataBuilder.append("&data.msg=" + URLEncoder.encode(message, "UTF-8"));// 제목

			byte[] postData = postDataBuilder.toString().getBytes("UTF8");

			URL url = new URL(host);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
			conn.setRequestProperty("Authorization", "GoogleLogin auth=" + auth);

			OutputStream out = conn.getOutputStream();
			out.write(postData);
			out.close();

			conn.getInputStream();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void pushText(List<Device> devices, String message) {
		for (Device device : devices) {
			pushText(device, message);
		}
	}

	@Override
	public void pushBadge(Device device, int badgeCount) {
		pushText(device, String.format(badgeText, badgeCount));
	}

}
